# /usr/bin/env python
# coding=utf8


import urllib.parse
# import ssl
import re
import hashlib
import urllib
import random
import http
import urllib.request
import json
import time
import map


# 生成MD5


def md5(str):
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))
    return hl.hexdigest()


def baidu(origin, to):
    appid = '20181008000216613'  # 你的appid
    secretKey = 'LeAI7CNG3dkartTn0aj3'  # 你的密钥
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    q = origin
    fromLang = 'zh'
    toLang = to
    salt = random.randint(32768, 65536)

    sign = appid + q + str(salt) + secretKey

    sign = md5(sign)
    myurl = myurl + '?appid=' + appid + '&q=' + \
            urllib.parse.quote(origin) + '&from=' + fromLang + '&to=' + toLang + \
            '&salt=' + str(salt) + '&sign=' + sign

    try:
        request = urllib.request.Request(myurl)
        f = urllib.request.urlopen(request)
        result = json.loads(f.read().decode('utf-8'))
        return result["trans_result"][0]["dst"]
    except Exception as e:
        print("翻译错误")


def huangBaidu(origin, to):
    if (to == 'en' and map.whitePaper.get(origin) != None):
        return map.whitePaper.get(origin)
    else:
        # for key, values in map.whitePaper.items():
        #     origin=origin.replace(key,values)
        fromLang = 'zh'
        appid = '20181008000216613'  # 参考百度翻译后台，申请appid和secretKey
        secretKey = 'LeAI7CNG3dkartTn0aj3'
        httpClient = None
        myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
        salt = random.randint(32768, 65536)
        sign = appid + origin + str(salt) + secretKey
        sign = sign.encode('UTF-8')
        m1 = hashlib.md5()
        m1.update(sign)
        sign = m1.hexdigest()
        myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
            origin) + '&from=' + fromLang + '&to=' + to + '&salt=' + str(salt) + '&sign=' + sign
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        html = response.read().decode('UTF-8')
        target2 = json.loads(html)
        print(target2)
        src = target2["trans_result"][0]["dst"]
        time.sleep(0.1)
        return src.replace("% s", "%s").replace("'", "\\'").replace("& gt;", "&gt;").replace("&gt；","&gt;")


baidu("你好", "en")
print(map.whitePaper.get('Alice1') == None)
